package com.enation.app.javashop.core.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.enation.app.javashop.core.member.model.dos.MemberVisitDataDO;
import com.enation.app.javashop.core.member.model.dto.MemberVisit;
import com.enation.app.javashop.core.member.service.MemberVisitDataManager;
import com.enation.app.javashop.core.payment.plugin.weixin.signaturer.WechatSignaturer;
import com.enation.app.javashop.core.payment.plugin.weixin.signaturer.WechatTypeEnmu;
import com.enation.app.javashop.framework.database.DaoSupport;
import com.enation.app.javashop.framework.util.DateUtil;
import com.enation.app.javashop.framework.util.HttpUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: zhou
 * @Date: 2020/9/14
 * @Description:
 */
@Service
public class MemberVisitDataManagerImpl implements MemberVisitDataManager {

    @Autowired
    private DaoSupport daoSupport;
    @Autowired
    private WechatSignaturer wechatSignaturer;
    protected final Log logger = LogFactory.getLog(this.getClass());
    @Override
    public void add(long time) {
        String timeString = DateUtil.toString(time, "yyyyMMdd");

        //获取数据
        String accessToken = wechatSignaturer.getCgiAccessToken(WechatTypeEnmu.MINI);
        String url = "https://api.weixin.qq.com/datacube/getweanalysisappiddailyretaininfo?access_token=" + accessToken;
        Map map = new HashMap();
        map.put("begin_date", timeString);
        map.put("end_date", timeString);
        String content = HttpUtils.doPostWithJson(url, map);
        logger.debug("获取日活数据成功："+content);
        MemberVisit response = JSON.parseObject(content, new TypeReference<MemberVisit>() {
        });
        List<Map<String, Integer>> visitNewMap = response.getVisitUvNew();
        List<Map<String, Integer>> visitMap = response.getVisitUv();
        //保存数据
        if (visitNewMap != null && visitMap != null && visitNewMap.size() > 0 && visitMap.size() > 0) {
            //新增用户留存
            Integer visitNew = visitNewMap.get(0).get("value");
            //活跃用户留存
            Integer visit = visitMap.get(0).get("value");
            String sql = "update es_sss_member_visit_data set visit_uv_new=? , visit_uv=? where create_time=?";
            int updateStatus = daoSupport.execute(sql, visitNew, visit, time);
            if (updateStatus <= 0) {
                MemberVisitDataDO memberVisitDataDO = new MemberVisitDataDO();
                memberVisitDataDO.setVisitUvNew(visitNew);
                memberVisitDataDO.setVisitUv(visit);
                memberVisitDataDO.setCreateTime(time);
                daoSupport.insert("es_sss_member_visit_data", memberVisitDataDO);
            }
        }
    }
}
